<template>
	<view class="container">
		<view class="status_bar">
			<view style="margin-left: 3%;" @tap="goBack()"><u-icon name="arrow-leftward" size='24' /></u-icon></view>
			<view style="font-weight: bold;margin-left: -56upx;">创建群</view>
			
			<view></view>
		</view>
		<view class="wrapper" style="overflow-y: auto;height: calc(100vh - 228px);">
			<view class="uni-list">
				<checkbox-group @change="checkboxChange">
					<label class="uni-list-cell" v-for="(item,index) in originalArray" :key="index">
						<view>
							<checkbox :value="item" :checked="item.checked" />
						</view>
						<image v-if="item.userAvatarFileName" style="width:50px;height: 50px;"
							:src="`http://chat.zwsmcn.com:8090/UserAvatarDownloader?action=ad&user_uid=${item.user_uid}&user_local_cached_avatar=${item.userAvatarFileName}&enforceDawnload=1`">
						</image>
						<view v-else class="name-img">{{item.nickname[0]}}</view>
						<view style="margin-left: 20upx;position: relative;">{{item.nickname}}</view>
					</label>
				</checkbox-group>
			</view>
			<view class="btn-box" @click="addcrowd()">创建群</view>

		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				owner_nickname: '',
				checkboxValue1: [],
				originalArray: [],
				checkedItems: [],
				checkListValue: [],
				saveShow: false
			}
		},
		onShow() {
			this.checkedItems = []
		},
		onLoad(props) {
			this.getfriendlist()
			console.log(uni.IMSDK.getLoginInfo());
		},
		methods: {
			// 获取好友
			getfriendlist() {
				const newDataObj = {
					"user_uid": uni.getStorageSync('user_uid'),
				};
				const newDataJsonStr = JSON.stringify(newDataObj)
				const requestData = {
					"processorId": '1008',
					"jobDispatchId": '2',
					"actionId": '7',
					"newData": uni.getStorageSync('user_uid')
				};
				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						console.log(JSON.parse(res.data.returnValue))
						this.originalArray = JSON.parse(res.data.returnValue)
						console.log(this.originalArray, "3213-=-=-=-=")
					},
					fail: res => {
						console.log(res);
					}
				});
			},
			checkboxChange(e) {
				const checkedArray = e.detail.value;
				console.log(checkedArray);
				this.checkedItems = [];
				// const currentCheckedItems = [...this.checkedItems]; // 创建当前checkedItems的副本用于遍历
				// // 先处理取消选中的情况，从checkedItems中删除当前未选中的项
				// currentCheckedItems.forEach((checkedItem, index) => {
				// 	if (!checkedArray.includes(checkedItem)) {
				// 		// 如果在当前checkedItems中存在，但不在新的选中项数组中，说明取消选中了，删除该项
				// 		this.checkedItems.splice(index, 1);
				// 	}
				// });
				// 再处理选中的情况，添加新选中的项到checkedItems
				checkedArray.forEach(newCheckedItem => {

					// this.checkedItems.push(newCheckedItem);
					this.checkedItems.push({
						user_uid: newCheckedItem.user_uid,
						userAvatarFileName: newCheckedItem.userAvatarFileName || "",
						nickname: newCheckedItem.nickname || "",
					});

				});
				console.log(this.checkedItems);
				// 这里可以根据需求进一步处理选中的数据，比如赋值给其他响应式数据等
				// 例如：this.selectedItems = this.checkedItems;
			},
			// 添加群
			addcrowd() {
				console.log(this.checkedItems, "-=-=-=-")
				this.checkedItems.push({
					user_uid: uni.getStorageSync('user_uid'),
					userAvatarFileName: uni.getStorageSync('user_avatar_file_name') || "",
					nickname: uni.getStorageSync('nickname') || "",
				})
				const newDataObj = {
					"owner_uid": uni.getStorageSync('user_uid'), // 创建者（群主）的 uid
					"owner_nickname": uni.getStorageSync('nickname'),
					"members": JSON.stringify(this.checkedItems),
				};
				const newDataJsonStr = JSON.stringify(newDataObj)
				const requestData = {
					"processorId": '1016',
					"jobDispatchId": '24',
					"actionId": '7',
					"newData": newDataJsonStr
				};
				const requestDataJsonStr = JSON.stringify(requestData);
				console.log(requestDataJsonStr)
				uni.request({
					// url: 'http://chat.zwsmcn.com:8090/rest_post',
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					header: {
						'content-type': 'application/json'
					},
					data: requestData, // requestDataJsonStr,
					method: 'POST',
					success: res => {
						console.log(res)
						if (res.data.success) {
							console.log(JSON.parse(res.data.returnValue))
							let item = JSON.parse(res.data.returnValue);

							let srcNickName = uni.getStorageSync('nickname') ?? '';
							let from_user_avatar = uni.getStorageSync('user_avatar_file_name') ?? '';;

							let at = [];
							let chat_type = 90;
							let typeu = 46;
							let message = {};
							message.inviteBeUid = item.g_owner_user_uid
							message.initveBeNickName = item.g_owner_name
							message.g_id = item.g_id
							message.g_status = item.g_status
							message.g_name = item.g_name
							message.g_owner_user_uid = item.g_owner_user_uid
							message.g_notice = item.g_notice
							message.g_member_count = item.g_member_count
							message.create_user_name = item.g_owner_name
							message.create_time = item.create_time
							message.g_owner_name = item.g_owner_name
							message.nickname_ingroup = item.nickname_ingroup
							message.imIsInGroup = item.imIsInGroup
							message.g_notice_updatetime = item.g_notice_updatetime
							message.g_notice_updateuid = item.g_notice_updateuid
							message.g_notice_updatenick = item.g_notice_updatenick
							message.ty = 90;

							// let dataContent = this.senddataContent(typeu, message, chat_type, 0,at,item.g_id);
							let p = uni.MBProtocalFactory.createGroupDataSimple(uni.IMSDK.getLoginInfo()
								.loginUserId,
								srcNickName, item.g_id, message,
								typeu, at, chat_type, 0);
							console.log(p);
							p.time = uni.MBUtils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
							p.gid = item.g_id;
							this.insertTableData(p)

							this.$util.toast('添加成功')
							setTimeout(() => {
								uni.navigateBack({
									delta: 1, // 返回上一级页面
								});
							}, 1000);
						}

					},
					fail: res => {
						console.log(res);
					}
				});
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			//删除
			handleDelete(id) {
				this.checkListValue = this.checkListValue.filter(item => item.id !== id);
			},

			senddataContent(typeu, dataContent, chat_type, contentDuration, at, to_user_id) {
				let from_user_id = uni.IMSDK.getLoginInfo().loginUserId;

				let from_user_nickname = uni.getStorageSync('nickname') ?? '';;
				let from_user_avatar = uni.getStorageSync('user_avatar_file_name') ?? '';;
				var dataContent_z = {};
				let fingerPrint = null
				let QoS = true;
				if (typeu == 3) {
					dataContent_z.t = to_user_id;
					dataContent_z.cy = 2;
					dataContent_z.m = dataContent;
					dataContent_z.ty = chat_type;
					dataContent_z.quote_status = 0;
					dataContent_z.quote_type = 0;
					dataContent_z.quote_fp = '';
					dataContent_z.quote_sender_uid = '';
					dataContent_z.quote_sender_nick = '';
					dataContent_z.quote_content = ''; //quote_content
					dataContent_z.f = from_user_id;
					if (chat_type == 2) {
						dataContent_z.contentDuration = contentDuration;
					}

					dataContent_z.nickName = from_user_nickname;
					dataContent_z.userAvatar = from_user_avatar;
					dataContent_z.receivernickName = this.info.nickname ?? '';
					dataContent_z.receiveruserAvatar = this.info.userAvatar ?? '';


				} else {
					dataContent_z.at = at;
					dataContent_z.QoS = QoS;
					dataContent_z.nickName = from_user_nickname;
					dataContent_z.userAvatar = from_user_avatar;
					dataContent_z.receivernickName = this.info.g_name;
					dataContent_z.receiveruserAvatar = this.info.image ?? this.info.userAvatar;
					dataContent_z.cy = 2;
					dataContent_z.f = from_user_id;
					dataContent_z.m = dataContent;
					dataContent_z.t = to_user_id;
					dataContent_z.ty = chat_type;
					dataContent_z.quote_status = 0;
					dataContent_z.quote_type = 0;
					dataContent_z.quote_fp = '';
					dataContent_z.quote_sender_uid = '';
					dataContent_z.quote_sender_nick = '';
					dataContent_z.quote_content = '';
					if (chat_type == 2) {
						dataContent_z.contentDuration = contentDuration;
					}


				}

				return dataContent_z;
			},
			// 新增表数据
			insertTableData(p) {
				console.log(p)
				let open = this.DB.isOpen();
				if (open) {
					let arr = []
					arr.push(p)
					// 如果需要根据p参数插入新数据，可以在这里正确处理p与arr的关系，例如arr.push(p)等操作

					arr.map(item => {
						console.log(item, 'arr-=-=-=-=-=arr-=-=-=-')
						let dataContent = JSON.parse(item.dataContent);
						let chat_type = dataContent.ty

						let time = uni.MBUtils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
						let sm = 0;
						if (item.sm) {
							sm = item.sm;
						}
						let is_read = p.is_read ?? 0;

						if (item.from == this.fromUserId) {
							is_read = 1;
						}

						let relatedId = '';
						if (!item.gid || item.gid == '0') {
							if (item.from == uni.getStorageSync('user_uid')) {
								relatedId = item.to;
							} else {
								relatedId = item.from;
							}
						} else {
							relatedId = item.gid;
						}

						let sql =
							`'${item.type}', '${item.dataContent}', '${item.from}', '${item.to}', '${item.QoS}', '${item.typeu}', '${sm}', '${item.fp}', '${item.retryCount}', '${time}', '${item.gid}',0,0, '${chat_type}',${is_read},'${relatedId}'`;
						console.log(sql, "-=-=-=-=-=sas")
						// this.info
						let condition =
							'type, dataContent, from1, to1, QoS, typeu, sm, fp, retryCount, time, gid,is_collect,del_flag,chat_type,is_read,relatedId';
						// 新增 DB.insertTableData(表名, 对应表头列的数据)

						console.log('insertTableData4')
						this.DB.insertTableData("chat" + uni.getStorageSync("user_uid"), sql, condition)
							.then(res => {
								console.log("新增数据成功");
								// this.selectTableData();
							})
							.catch(error => {
								console.log("失败", error);
							});
					})


				} else {
					this.$util.toast("数据库未打开");
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100%;
	}

	.status_bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 50upx;
	}

	.status_bar,
	.head {
		background-color: #fff;
		height: 160upx;

		.face {
			width: 160upx;
			height: 160upx;
			border-radius: 10upx;
		}

		.info-name {
			font-size: 40upx;
			font-weight: bold;
		}

		.info-num {
			padding: 2upx 30upx;
			background: #f0f4f7;
			border-radius: 30upx;
			margin-top: 21upx;
		}

		.copybtns {
			color: #4457a4;
			margin-top: 21upx;
		}
	}

	.wrapper {
		width: 92%;
		margin-left: 4%;

		// .select-box {
		// 	margin: 10upx 1% 0 2%;
		// 	display: flex;
		// 	justify-content: space-around;
		// 	align-items: center;
		// }
		.uni-list-cell {
			justify-content: flex-start;
			display: flex;
			align-items: center;
			padding: 30upx;
			margin-top: 30upx;
		}

		.name-img {
			width: 80upx;
			height: 80upx;
			border-radius: 10upx;
			background: #d54827;
			font-size: 36upx;
			text-align: center;
			line-height: 80upx;
			color: #fff;
			margin-left: 10upx;
		}

		.img-value {
			border-radius: 30upx;
			margin-left: 10upx;
			display: flex;
			margin-top: 30upx;

			.img-value1 {
				margin-left: 30upx;
				position: relative;
			}

			.delete-btn {
				position: absolute;
				top: -16%;
				left: 76%;
			}
		}
	}




	.clear-record-box {
		border-radius: 30upx;
		padding: 30upx;

		.clear-record-box-title {
			padding: 10upx 20upx;
			font-size: 40upx;
		}

		.clear-record-box-title1 {
			padding: 20upx 0 30upx 20upx;
			font-size: 30upx;
			font-weight: 300;
		}

		.clear-record-box-btn {
			display: flex;
			// padding: 30upx 0 20upx 0;
			margin-left: 150upx;
			margin-top: 30upx;
		}

		.clear-record-box-btn-left {
			padding: 10upx 30upx;
		}

		.clear-record-box-btn-right {
			background: #000;
			color: #fff;
			padding: 10upx 40upx;
			margin-left: 30upx;
		}
	}

	.btn-box {
		width: 92%;
		// margin-left: 4%;
		background: #000;
		opacity: 0.6;
		color: #fff;
		text-align: center;
		height: 80upx;
		line-height: 80upx;
		border-radius: 20upx;
		position: fixed;
		bottom: 20upx;
	}
</style>